home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / regrtest.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  20.3 KB  |  742 lines

  1. #! /usr/bin/env python
  2.  
  3. """Regression test.
  4.  
  5. This will find all modules whose name is "test_*" in the test
  6. directory, and run them.  Various command line options provide
  7. additional facilities.
  8.  
  9. Command line options:
  10.  
  11. -v: verbose   -- run tests in verbose mode with output to stdout
  12. -q: quiet     -- don't print anything except if a test fails
  13. -g: generate  -- write the output file for a test instead of comparing it
  14. -x: exclude   -- arguments are tests to *exclude*
  15. -s: single    -- run only a single test (see below)
  16. -r: random    -- randomize test execution order
  17. -l: findleaks -- if GC is available detect tests that leak memory
  18. -u: use       -- specify which special resource intensive tests to run
  19. -h: help      -- print this text and exit
  20.  
  21. If non-option arguments are present, they are names for tests to run,
  22. unless -x is given, in which case they are names for tests not to run.
  23. If no test names are given, all tests are run.
  24.  
  25. -v is incompatible with -g and does not compare test output files.
  26.  
  27. -s means to run only a single test and exit.  This is useful when doing memory
  28. analysis on the Python interpreter (which tend to consume to many resources to
  29. run the full regression test non-stop).  The file /tmp/pynexttest is read to
  30. find the next test to run.  If this file is missing, the first test_*.py file
  31. in testdir or on the command line is used.  (actually tempfile.gettempdir() is
  32. used instead of /tmp).
  33.  
  34. -u is used to specify which special resource intensive tests to run, such as
  35. those requiring large file support or network connectivity.  The argument is a
  36. comma-separated list of words indicating the resources to test.  Currently
  37. only the following are defined:
  38.  
  39.     curses -    Tests that use curses and will modify the terminal's
  40.                 state and output modes.
  41.  
  42.     largefile - It is okay to run some test that may create huge files.  These
  43.                 tests can take a long time and may consume >2GB of disk space
  44.                 temporarily.
  45.  
  46.     network -   It is okay to run tests that use external network resource,
  47.                 e.g. testing SSL support for sockets.
  48. """
  49.  
  50. import sys
  51. import os
  52. import getopt
  53. import traceback
  54. import random
  55. import StringIO
  56.  
  57. import test_support
  58.  
  59. def usage(code, msg=''):
  60.     print __doc__
  61.     if msg: print msg
  62.     sys.exit(code)
  63.  
  64.  
  65. def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0,
  66.          exclude=0, single=0, randomize=0, findleaks=0,
  67.          use_resources=None):
  68.     """Execute a test suite.
  69.  
  70.     This also parses command-line options and modifies its behavior
  71.     accordingly.
  72.  
  73.     tests -- a list of strings containing test names (optional)
  74.     testdir -- the directory in which to look for tests (optional)
  75.  
  76.     Users other than the Python test suite will certainly want to
  77.     specify testdir; if it's omitted, the directory containing the
  78.     Python test suite is searched for.
  79.  
  80.     If the tests argument is omitted, the tests listed on the
  81.     command-line will be used.  If that's empty, too, then all *.py
  82.     files beginning with test_ will be used.
  83.  
  84.     The other default arguments (verbose, quiet, generate, exclude, single,
  85.     randomize, findleaks, and use_resources) allow programmers calling main()
  86.     directly to set the values that would normally be set by flags on the
  87.     command line.
  88.  
  89.     """
  90.  
  91.     test_support.record_original_stdout(sys.stdout)
  92.     try:
  93.         opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrlu:',
  94.                                    ['help', 'verbose', 'quiet', 'generate',
  95.                                     'exclude', 'single', 'random',
  96.                                     'findleaks', 'use='])
  97.     except getopt.error, msg:
  98.         usage(2, msg)
  99.  
  100.     # Defaults
  101.     if use_resources is None:
  102.         use_resources = []
  103.     for o, a in opts:
  104.         if o in ('-h', '--help'):
  105.             usage(0)
  106.         elif o in ('-v', '--verbose'):
  107.             verbose += 1
  108.         elif o in ('-q', '--quiet'):
  109.             quiet = 1;
  110.             verbose = 0
  111.         elif o in ('-g', '--generate'):
  112.             generate = 1
  113.         elif o in ('-x', '--exclude'):
  114.             exclude = 1
  115.         elif o in ('-s', '--single'):
  116.             single = 1
  117.         elif o in ('-r', '--randomize'):
  118.             randomize = 1
  119.         elif o in ('-l', '--findleaks'):
  120.             findleaks = 1
  121.         elif o in ('-u', '--use'):
  122.             u = [x.lower() for x in a.split(',')]
  123.             for r in u:
  124.                 if r not in ('curses', 'largefile', 'network'):
  125.                     usage(1, 'Invalid -u/--use option: %s' % a)
  126.             use_resources.extend(u)
  127.     if generate and verbose:
  128.         usage(2, "-g and -v don't go together!")
  129.  
  130.     good = []
  131.     bad = []
  132.     skipped = []
  133.  
  134.     if findleaks:
  135.         try:
  136.             import gc
  137.         except ImportError:
  138.             print 'No GC available, disabling findleaks.'
  139.             findleaks = 0
  140.         else:
  141.             # Uncomment the line below to report garbage that is not
  142.             # freeable by reference counting alone.  By default only
  143.             # garbage that is not collectable by the GC is reported.
  144.             #gc.set_debug(gc.DEBUG_SAVEALL)
  145.             found_garbage = []
  146.  
  147.     if single:
  148.         from tempfile import gettempdir
  149.         filename = os.path.join(gettempdir(), 'pynexttest')
  150.         try:
  151.             fp = open(filename, 'r')
  152.             next = fp.read().strip()
  153.             tests = [next]
  154.             fp.close()
  155.         except IOError:
  156.             pass
  157.     for i in range(len(args)):
  158.         # Strip trailing ".py" from arguments
  159.         if args[i][-3:] == os.extsep+'py':
  160.             args[i] = args[i][:-3]
  161.     stdtests = STDTESTS[:]
  162.     nottests = NOTTESTS[:]
  163.     if exclude:
  164.         for arg in args:
  165.             if arg in stdtests:
  166.                 stdtests.remove(arg)
  167.         nottests[:0] = args
  168.         args = []
  169.     tests = tests or args or findtests(testdir, stdtests, nottests)
  170.     if single:
  171.         tests = tests[:1]
  172.     if randomize:
  173.         random.shuffle(tests)
  174.     test_support.verbose = verbose      # Tell tests to be moderately quiet
  175.     test_support.use_resources = use_resources
  176.     save_modules = sys.modules.keys()
  177.     for test in tests:
  178.         if not quiet:
  179.             print test
  180.             sys.stdout.flush()
  181.         ok = runtest(test, generate, verbose, quiet, testdir)
  182.         if ok > 0:
  183.             good.append(test)
  184.         elif ok == 0:
  185.             bad.append(test)
  186.         else:
  187.             skipped.append(test)
  188.         if findleaks:
  189.             gc.collect()
  190.             if gc.garbage:
  191.                 print "Warning: test created", len(gc.garbage),
  192.                 print "uncollectable object(s)."
  193.                 # move the uncollectable objects somewhere so we don't see
  194.                 # them again
  195.                 found_garbage.extend(gc.garbage)
  196.                 del gc.garbage[:]
  197.         # Unload the newly imported modules (best effort finalization)
  198.         for module in sys.modules.keys():
  199.             if module not in save_modules and module.startswith("test."):
  200.                 test_support.unload(module)
  201.  
  202.     # The lists won't be sorted if running with -r
  203.     good.sort()
  204.     bad.sort()
  205.     skipped.sort()
  206.  
  207.     if good and not quiet:
  208.         if not bad and not skipped and len(good) > 1:
  209.             print "All",
  210.         print count(len(good), "test"), "OK."
  211.         if verbose:
  212.             print "CAUTION:  stdout isn't compared in verbose mode:  a test"
  213.             print "that passes in verbose mode may fail without it."
  214.     if bad:
  215.         print count(len(bad), "test"), "failed:"
  216.         printlist(bad)
  217.     if skipped and not quiet:
  218.         print count(len(skipped), "test"), "skipped:"
  219.         printlist(skipped)
  220.  
  221.         e = _ExpectedSkips()
  222.         plat = sys.platform
  223.         if e.isvalid():
  224.             surprise = _Set(skipped) - e.getexpected()
  225.             if surprise:
  226.                 print count(len(surprise), "skip"), \
  227.                       "unexpected on", plat + ":"
  228.                 printlist(surprise)
  229.             else:
  230.                 print "Those skips are all expected on", plat + "."
  231.         else:
  232.             print "Ask someone to teach regrtest.py about which tests are"
  233.             print "expected to get skipped on", plat + "."
  234.  
  235.     if single:
  236.         alltests = findtests(testdir, stdtests, nottests)
  237.         for i in range(len(alltests)):
  238.             if tests[0] == alltests[i]:
  239.                 if i == len(alltests) - 1:
  240.                     os.unlink(filename)
  241.                 else:
  242.                     fp = open(filename, 'w')
  243.                     fp.write(alltests[i+1] + '\n')
  244.                     fp.close()
  245.                 break
  246.         else:
  247.             os.unlink(filename)
  248.  
  249.     sys.exit(len(bad) > 0)
  250.  
  251.  
  252. STDTESTS = [
  253.     'test_grammar',
  254.     'test_opcodes',
  255.     'test_operations',
  256.     'test_builtin',
  257.     'test_exceptions',
  258.     'test_types',
  259.    ]
  260.  
  261. NOTTESTS = [
  262.     'test_support',
  263.     'test_b1',
  264.     'test_b2',
  265.     'test_future1',
  266.     'test_future2',
  267.     'test_future3',
  268.     ]
  269.  
  270. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  271.     """Return a list of all applicable test modules."""
  272.     if not testdir: testdir = findtestdir()
  273.     names = os.listdir(testdir)
  274.     tests = []
  275.     for name in names:
  276.         if name[:5] == "test_" and name[-3:] == os.extsep+"py":
  277.             modname = name[:-3]
  278.             if modname not in stdtests and modname not in nottests:
  279.                 tests.append(modname)
  280.     tests.sort()
  281.     return stdtests + tests
  282.  
  283. def runtest(test, generate, verbose, quiet, testdir = None):
  284.     """Run a single test.
  285.     test -- the name of the test
  286.     generate -- if true, generate output, instead of running the test
  287.     and comparing it to a previously created output file
  288.     verbose -- if true, print more messages
  289.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  290.     testdir -- test directory
  291.     """
  292.     test_support.unload(test)
  293.     if not testdir: testdir = findtestdir()
  294.     outputdir = os.path.join(testdir, "output")
  295.     outputfile = os.path.join(outputdir, test)
  296.     if verbose:
  297.         cfp = None
  298.     else:
  299.         cfp = StringIO.StringIO()
  300.     try:
  301.         save_stdout = sys.stdout
  302.         try:
  303.             if cfp:
  304.                 sys.stdout = cfp
  305.                 print test              # Output file starts with test name
  306.             the_module = __import__(test, globals(), locals(), [])
  307.             # Most tests run to completion simply as a side-effect of
  308.             # being imported.  For the benefit of tests that can't run
  309.             # that way (like test_threaded_import), explicitly invoke
  310.             # their test_main() function (if it exists).
  311.             indirect_test = getattr(the_module, "test_main", None)
  312.             if indirect_test is not None:
  313.                 indirect_test()
  314.         finally:
  315.             sys.stdout = save_stdout
  316.     except (ImportError, test_support.TestSkipped), msg:
  317.         if not quiet:
  318.             print "test", test, "skipped --", msg
  319.             sys.stdout.flush()
  320.         return -1
  321.     except KeyboardInterrupt:
  322.         raise
  323.     except test_support.TestFailed, msg:
  324.         print "test", test, "failed --", msg
  325.         sys.stdout.flush()
  326.         return 0
  327.     except:
  328.         type, value = sys.exc_info()[:2]
  329.         print "test", test, "crashed --", str(type) + ":", value
  330.         sys.stdout.flush()
  331.         if verbose:
  332.             traceback.print_exc(file=sys.stdout)
  333.             sys.stdout.flush()
  334.         return 0
  335.     else:
  336.         if not cfp:
  337.             return 1
  338.         output = cfp.getvalue()
  339.         if generate:
  340.             if output == test + "\n":
  341.                 if os.path.exists(outputfile):
  342.                     # Write it since it already exists (and the contents
  343.                     # may have changed), but let the user know it isn't
  344.                     # needed:
  345.                     print "output file", outputfile, \
  346.                           "is no longer needed; consider removing it"
  347.                 else:
  348.                     # We don't need it, so don't create it.
  349.                     return 1
  350.             fp = open(outputfile, "w")
  351.             fp.write(output)
  352.             fp.close()
  353.             return 1
  354.         if os.path.exists(outputfile):
  355.             fp = open(outputfile, "r")
  356.             expected = fp.read()
  357.             fp.close()
  358.         else:
  359.             expected = test + "\n"
  360.         if output == expected:
  361.             return 1
  362.         print "test", test, "produced unexpected output:"
  363.         sys.stdout.flush()
  364.         reportdiff(expected, output)
  365.         sys.stdout.flush()
  366.         return 0
  367.  
  368. def reportdiff(expected, output):
  369.     import difflib
  370.     print "*" * 70
  371.     a = expected.splitlines(1)
  372.     b = output.splitlines(1)
  373.     sm = difflib.SequenceMatcher(a=a, b=b)
  374.     tuples = sm.get_opcodes()
  375.  
  376.     def pair(x0, x1):
  377.         # x0:x1 are 0-based slice indices; convert to 1-based line indices.
  378.         x0 += 1
  379.         if x0 >= x1:
  380.             return "line " + str(x0)
  381.         else:
  382.             return "lines %d-%d" % (x0, x1)
  383.  
  384.     for op, a0, a1, b0, b1 in tuples:
  385.         if op == 'equal':
  386.             pass
  387.  
  388.         elif op == 'delete':
  389.             print "***", pair(a0, a1), "of expected output missing:"
  390.             for line in a[a0:a1]:
  391.                 print "-", line,
  392.  
  393.         elif op == 'replace':
  394.             print "*** mismatch between", pair(a0, a1), "of expected", \
  395.                   "output and", pair(b0, b1), "of actual output:"
  396.             for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
  397.                 print line,
  398.  
  399.         elif op == 'insert':
  400.             print "***", pair(b0, b1), "of actual output doesn't appear", \
  401.                   "in expected output after line", str(a1)+":"
  402.             for line in b[b0:b1]:
  403.                 print "+", line,
  404.  
  405.         else:
  406.             print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
  407.  
  408.     print "*" * 70
  409.  
  410. def findtestdir():
  411.     if __name__ == '__main__':
  412.         file = sys.argv[0]
  413.     else:
  414.         file = __file__
  415.     testdir = os.path.dirname(file) or os.curdir
  416.     return testdir
  417.  
  418. def count(n, word):
  419.     if n == 1:
  420.         return "%d %s" % (n, word)
  421.     else:
  422.         return "%d %ss" % (n, word)
  423.  
  424. def printlist(x, width=70, indent=4):
  425.     """Print the elements of a sequence to stdout.
  426.  
  427.     Optional arg width (default 70) is the maximum line length.
  428.     Optional arg indent (default 4) is the number of blanks with which to
  429.     begin each line.
  430.     """
  431.  
  432.     line = ' ' * indent
  433.     for one in map(str, x):
  434.         w = len(line) + len(one)
  435.         if line[-1:] == ' ':
  436.             pad = ''
  437.         else:
  438.             pad = ' '
  439.             w += 1
  440.         if w > width:
  441.             print line
  442.             line = ' ' * indent + one
  443.         else:
  444.             line += pad + one
  445.     if len(line) > indent:
  446.         print line
  447.  
  448. class _Set:
  449.     def __init__(self, seq=[]):
  450.         data = self.data = {}
  451.         for x in seq:
  452.             data[x] = 1
  453.  
  454.     def __len__(self):
  455.         return len(self.data)
  456.  
  457.     def __sub__(self, other):
  458.         "Return set of all elements in self not in other."
  459.         result = _Set()
  460.         data = result.data = self.data.copy()
  461.         for x in other.data:
  462.             if x in data:
  463.                 del data[x]
  464.         return result
  465.  
  466.     def __iter__(self):
  467.         return iter(self.data)
  468.  
  469.     def tolist(self, sorted=1):
  470.         "Return _Set elements as a list."
  471.         data = self.data.keys()
  472.         if sorted:
  473.             data.sort()
  474.         return data
  475.  
  476. _expectations = {
  477.     'win32':
  478.         """
  479.         test_al
  480.         test_cd
  481.         test_cl
  482.         test_commands
  483.         test_crypt
  484.         test_curses
  485.         test_dbm
  486.         test_dl
  487.         test_email_codecs
  488.         test_fcntl
  489.         test_fork1
  490.         test_gdbm
  491.         test_gl
  492.         test_grp
  493.         test_imgfile
  494.         test_largefile
  495.         test_linuxaudiodev
  496.         test_mhlib
  497.         test_nis
  498.         test_openpty
  499.         test_poll
  500.         test_pty
  501.         test_pwd
  502.         test_signal
  503.         test_socket_ssl
  504.         test_socketserver
  505.         test_sunaudiodev
  506.         test_timing
  507.         """,
  508.     'linux2':
  509.         """
  510.         test_al
  511.         test_cd
  512.         test_cl
  513.         test_curses
  514.         test_dl
  515.         test_email_codecs
  516.         test_gl
  517.         test_imgfile
  518.         test_largefile
  519.         test_nis
  520.         test_ntpath
  521.         test_socket_ssl
  522.         test_socketserver
  523.         test_sunaudiodev
  524.         test_unicode_file
  525.         test_winreg
  526.         test_winsound
  527.         """,
  528.    'mac':
  529.         """
  530.         test_al
  531.         test_bsddb
  532.         test_cd
  533.         test_cl
  534.         test_commands
  535.         test_crypt
  536.         test_curses
  537.         test_dbm
  538.         test_dl
  539.         test_email_codecs
  540.         test_fcntl
  541.         test_fork1
  542.         test_gl
  543.         test_grp
  544.         test_imgfile
  545.         test_largefile
  546.         test_linuxaudiodev
  547.         test_locale
  548.         test_mmap
  549.         test_nis
  550.         test_ntpath
  551.         test_openpty
  552.         test_poll
  553.         test_popen2
  554.         test_pty
  555.         test_pwd
  556.         test_signal
  557.         test_socket_ssl
  558.         test_socketserver
  559.         test_sunaudiodev
  560.         test_sundry
  561.         test_timing
  562.         test_unicode_file
  563.         test_winreg
  564.         test_winsound
  565.         """,
  566.     'unixware7':
  567.         """
  568.         test_al
  569.         test_bsddb
  570.         test_cd
  571.         test_cl
  572.         test_dl
  573.         test_email_codecs
  574.         test_gl
  575.         test_imgfile
  576.         test_largefile
  577.         test_linuxaudiodev
  578.         test_minidom
  579.         test_nis
  580.         test_ntpath
  581.         test_openpty
  582.         test_pyexpat
  583.         test_sax
  584.         test_socketserver
  585.         test_sunaudiodev
  586.         test_sundry
  587.         test_unicode_file
  588.         test_winreg
  589.         test_winsound
  590.         """,
  591.     'openunix8':
  592.         """
  593.         test_al
  594.         test_bsddb
  595.         test_cd
  596.         test_cl
  597.         test_dl
  598.         test_email_codecs
  599.         test_gl
  600.         test_imgfile
  601.         test_largefile
  602.         test_linuxaudiodev
  603.         test_minidom
  604.         test_nis
  605.         test_ntpath
  606.         test_openpty
  607.         test_pyexpat
  608.         test_sax
  609.         test_socketserver
  610.         test_sunaudiodev
  611.         test_sundry
  612.         test_unicode_file
  613.         test_winreg
  614.         test_winsound
  615.         """,
  616.     'sco_sv3':
  617.         """
  618.         test_al
  619.         test_asynchat
  620.         test_bsddb
  621.         test_cd
  622.         test_cl
  623.         test_dl
  624.         test_email_codecs
  625.         test_fork1
  626.         test_gettext
  627.         test_gl
  628.         test_imgfile
  629.         test_largefile
  630.         test_linuxaudiodev
  631.         test_locale
  632.         test_minidom
  633.         test_nis
  634.         test_ntpath
  635.         test_openpty
  636.         test_pyexpat
  637.         test_queue
  638.         test_sax
  639.         test_socketserver
  640.         test_sunaudiodev
  641.         test_sundry
  642.         test_thread
  643.         test_threaded_import
  644.         test_threadedtempfile
  645.         test_threading
  646.         test_unicode_file
  647.         test_winreg
  648.         test_winsound
  649.         """,
  650.     'riscos':
  651.         """
  652.         test_al
  653.         test_asynchat
  654.         test_bsddb
  655.         test_cd
  656.         test_cl
  657.         test_commands
  658.         test_crypt
  659.         test_dbm
  660.         test_dl
  661.         test_email_codecs
  662.         test_fcntl
  663.         test_fork1
  664.         test_gdbm
  665.         test_gl
  666.         test_grp
  667.         test_imgfile
  668.         test_largefile
  669.         test_linuxaudiodev
  670.         test_locale
  671.         test_mmap
  672.         test_nis
  673.         test_ntpath
  674.         test_openpty
  675.         test_poll
  676.         test_popen2
  677.         test_pty
  678.         test_pwd
  679.         test_socket_ssl
  680.         test_socketserver
  681.         test_strop
  682.         test_sunaudiodev
  683.         test_sundry
  684.         test_thread
  685.         test_threaded_import
  686.         test_threadedtempfile
  687.         test_threading
  688.         test_timing
  689.         test_unicode_file
  690.         test_winreg
  691.         test_winsound
  692.         """,
  693.     'darwin':
  694.         """
  695.         test_al
  696.         test_cd
  697.         test_cl
  698.         test_curses
  699.         test_dl
  700.         test_email_codecs
  701.         test_gdbm
  702.         test_gl
  703.         test_imgfile
  704.         test_largefile
  705.         test_linuxaudiodev
  706.         test_minidom
  707.         test_nis
  708.         test_ntpath
  709.         test_poll
  710.         test_socket_ssl
  711.         test_socketserver
  712.         test_sunaudiodev
  713.         test_unicode_file
  714.         test_winreg
  715.         test_winsound
  716.         """,
  717. }
  718.  
  719. class _ExpectedSkips:
  720.     def __init__(self):
  721.         self.valid = 0
  722.         if _expectations.has_key(sys.platform):
  723.             s = _expectations[sys.platform]
  724.             self.expected = _Set(s.split())
  725.             self.valid = 1
  726.  
  727.     def isvalid(self):
  728.         "Return true iff _ExpectedSkips knows about the current platform."
  729.         return self.valid
  730.  
  731.     def getexpected(self):
  732.         """Return set of test names we expect to skip on current platform.
  733.  
  734.         self.isvalid() must be true.
  735.         """
  736.  
  737.         assert self.isvalid()
  738.         return self.expected
  739.  
  740. if __name__ == '__main__':
  741.     main()
  742.